<template>
  <div class="question-history">
    <van-nav-bar
      title="答题历史记录"
      left-text="返回"
      left-arrow
      fixed
      @click-left="$router.go(-1)"
    />
    
    <div class="content-wrapper">
      <div class="stats-card">
        <div class="stat-item" v-for="stat in stats" :key="stat.label">
          <div class="stat-value">{{ stat.value }}</div>
          <div class="stat-label">{{ stat.label }}</div>
        </div>
      </div>
      
      <div class="search-section">
        <van-search
          v-model="searchQuery"
          placeholder="搜索题目内容"
          shape="round"
          background="#f7f8fa"
          @search="handleSearch"
        />
        
        <van-dropdown-menu class="filter-menu">
          <van-dropdown-item
            v-model="filterCategory"
            :options="categoryOptions"
            @change="applyFilters"
          />
          <van-dropdown-item
            v-model="filterResult"
            :options="resultOptions"
            @change="applyFilters"
          />
          <van-dropdown-item
            v-model="sortBy"
            :options="sortOptions"
            @change="applySorting"
          />
        </van-dropdown-menu>
      </div>
      
      <div class="record-list">
        <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
          <van-list
            v-model:loading="loading"
            :finished="finished"
            finished-text="没有更多记录了"
            @load="loadMore"
          >
            <div 
              class="record-card" 
              v-for="record in filteredRecords" 
              :key="record.recordNo"
              @click="viewRecordDetails(record.recordNo)"
            >
              <div class="record-header">
                <div class="record-meta">
                  <van-tag 
                    round 
                    :color="getCategoryColor(record.categoryName)"
                    text-color="#fff"
                  >
                    {{ record.categoryName }}
                  </van-tag>
                  <span class="record-date">{{ record.date }}</span>
                </div>
                <div class="record-score">
                  <span class="score-value">{{ record.score }}分</span>
                  <div class="score-stars">
                    <van-rate
                      :model-value="record.score / 20"
                      allow-half
                      readonly
                      :size="14"
                      color="#ffd21e"
                      void-icon="star"
                      void-color="#eee"
                    />
                  </div>
                </div>
              </div>
              
              <div class="record-progress">
                <div class="progress-info">
                  <span>正确率: {{ calculateCorrectRate(record) }}%</span>
                  <span>用时: {{ formatDuration(Number(record.duration)) }}</span>
                </div>
                <van-progress
                  :percentage="calculateCorrectRate(record)"
                  stroke-width="6"
                  :show-pivot="false"
                  :color="getProgressColor(calculateCorrectRate(record))"
                />
              </div>
              
              <div class="correct-count">
                <span>答对 {{ record.correctCount }} 题 / 共 {{ record.totalQuestions }} 题</span>
              </div>
            </div>
          </van-list>
        </van-pull-refresh>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { showToast } from 'vant';
import { getPracticeHistoryList } from '@/api/record';

// 类型定义
interface RecordItem {
  recordNo: string;
  categoryNo: string;
  categoryName: string;
  score: number;
  correctCount: number;
  totalQuestions: number;
  duration: string;
  startTime: string;
  endTime: string;
  date?: string;
}

interface Category {
  categoryNo: string;
  categoryName: string;
  color: string;
}

interface StatItem {
  label: string;
  value: string | number;
}

const router = useRouter();

// 数据状态
const recordsList = ref<RecordItem[]>([]);
const records = ref<RecordItem[]>([]);
const categoriesList: Category[] = [
  { categoryNo: 'CAT001', categoryName: '民法', color: '#7232dd' },
  { categoryNo: 'CAT002', categoryName: '刑法', color: '#ee0a24' },
  { categoryNo: 'CAT003', categoryName: '行政法', color: '#1989fa' },
  { categoryNo: 'CAT004', categoryName: '宪法', color: '#ff976a' },
  { categoryNo: 'CAT005', categoryName: '经济法', color: '#07c160' }
];

// UI状态
const searchQuery = ref('');
const filterCategory = ref('all');
const filterResult = ref('all');
const sortBy = ref('date-desc');
const loading = ref(false);
const finished = ref(false);
const refreshing = ref(false);
const error = ref<string | null>(null);

// 统计信息
const stats = computed<StatItem[]>(() => [
  {
    label: '总练习次数',
    value: records.value.length
  },
  {
    label: '平均正确率',
    value: records.value.length > 0 
      ? Math.round(records.value.reduce((sum, r) => sum + (r.correctCount / r.totalQuestions), 0) / records.value.length * 100) + '%'
      : '0%'
  },
  {
    label: '总答题数',
    value: records.value.reduce((sum, r) => sum + r.totalQuestions, 0)
  },
]);

// 下拉选项
const categoryOptions = [
  { text: '全部分类', value: 'all' },
  ...categoriesList.map(c => ({
    text: c.categoryName,
    value: c.categoryName
  }))
];

const resultOptions = [
  { text: '全部结果', value: 'all' },
  { text: '优秀 (80-100分)', value: 'excellent' },
  { text: '良好 (60-79分)', value: 'good' },
  { text: '不及格 (<60分)', value: 'fail' }
];

const sortOptions = [
  { text: '最新优先', value: 'date-desc' },
  { text: '最旧优先', value: 'date-asc' },
  { text: '分数最高', value: 'score-desc' },
  { text: '分数最低', value: 'score-asc' },
  { text: '正确率最高', value: 'correct-desc' },
  { text: '正确率最低', value: 'correct-asc' }
];

// 计算属性 - 过滤和排序后的记录
const filteredRecords = computed(() => {
  let result = [...records.value];
  
  // 分类过滤
  if (filterCategory.value !== 'all') {
    result = result.filter(r => r.categoryName== filterCategory.value);
  }
  
  // 结果过滤
  if (filterResult.value !== 'all') {
    result = result.filter(r => {
      const score = r.score;
      switch (filterResult.value) {
        case 'excellent': return score >= 80;
        case 'good': return score >= 60 && score < 80;
        case 'fail': return score < 60;
        default: return true;
      }
    });
  }
  
 // 修改搜索过滤部分
if (searchQuery.value.trim()) {
  const query = searchQuery.value.toLowerCase().trim();
  result = result.filter(r => 
    r.categoryName.toLowerCase().includes(query) || 
    (r.date && r.date.toLowerCase().includes(query)) ||
    r.score.toString().includes(query) ||
    (typeof r.duration === 'string' && r.duration.toLowerCase().includes(query)) // 添加类型检查
  );
}
  
  // 排序逻辑
  return [...result].sort((a, b) => {
    const dateA = new Date(a.startTime).getTime();
    const dateB = new Date(b.startTime).getTime();
    
    switch (sortBy.value) {
      case 'date-desc': return dateB - dateA;
      case 'date-asc': return dateA - dateB;
      case 'score-desc': return b.score - a.score;
      case 'score-asc': return a.score - b.score;
      case 'correct-desc': 
        return (b.correctCount / b.totalQuestions) - (a.correctCount / a.totalQuestions);
      case 'correct-asc': 
        return (a.correctCount / a.totalQuestions) - (b.correctCount / b.totalQuestions);
      default: return 0;
    }
  });
});

/**
 * 获取用户的所有刷题历史记录列表
 */
const fetchPracticeHistory = async () => {
  try {
    loading.value = true;    
    const userNo = localStorage.getItem("userNo") || "";
    if (!userNo) {
      throw new Error("用户未登录");
    }
    const res = await getPracticeHistoryList(userNo);
    
    if (res.data.code === 200) {
      recordsList.value = res.data.data.map((item: any) => ({
        ...item,
        date: formatDate(item.startTime)
      }));
      records.value = [...recordsList.value];
    } else {
      throw new Error(res.message || "获取数据失败");
    }
  } catch (err: any) {
    error.value = err.message;
    console.error("获取练习记录失败:", err);
  } finally {
    loading.value = false;
  }
};

// 辅助函数
const formatDate = (dateString: string) => {
  const date = new Date(dateString);
  const month = date.getMonth() + 1;
  const day = date.getDate();
  return `${month}月${day}日`;
};

// 格式化时间，during
const formatDuration = (seconds: number) => {
  const mins = Math.floor(seconds / 60);
  const secs = seconds % 60;
  return `${mins}分${secs}秒`;
};

// 计算正确率
const calculateCorrectRate = (record: RecordItem) => {
  return Math.round((record.correctCount / record.totalQuestions) * 100);
};
// 计算分类颜色
const getCategoryColor = (categoryName: string) => {
  const category = categoriesList.find(c => c.categoryName === categoryName);
  return category ? category.color : '#66d8d1';
};

// 计算进度条颜色
const getProgressColor = (percentage: number) => {
  if (percentage >= 80) return '#07c160';
  if (percentage >= 60) return '#ff976a';
  return '#ee0a24';
};

/*****************************************************
 * 搜索、筛选、排序相关逻辑
 * 前端实现的搜索、筛选、排序功能
 *****************************************************/
// 搜索相关
const handleSearch = () => {
  showToast(`搜索: ${searchQuery.value}`);
};
// 筛选相关
const applyFilters = () => {
  console.log('应用筛选:', { 
    category: filterCategory.value, 
    result: filterResult.value 
  });
};
// 排序相关
const applySorting = () => {
  console.log('应用排序:', sortBy.value);
};

//加载更多相关
const loadMore = () => {
  loading.value = false;
};

// 刷新相关
const onRefresh = () => {
  refreshing.value = true;
  setTimeout(() => {
    records.value = [...recordsList.value];
    refreshing.value = false;
    finished.value = false;
  }, 1000);
};

// 记录详情相关
const viewRecordDetails = (recordNo: string) => {
  router.push(`/recordDetail/${recordNo}`);
};

// 初始化
onMounted(() => {
  fetchPracticeHistory();
});
</script>

<style scoped>
.question-history {
  padding-top: 10px;
  padding-bottom: 20px;
  min-height: 100vh;
  background-color: #f7f8fa;
}

.content-wrapper {
  padding: 0 12px;
}

.stats-card {
  display: flex;
  justify-content: space-between;
  background: linear-gradient(135deg, #1976D2, #2196F3);
  border-radius: 12px;
  padding: 16px;
  margin: 12px 0;
  box-shadow: 0 4px 12px rgba(25, 118, 210, 0.2);
}

.stat-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  flex: 1;
}

.stat-value {
  font-size: 20px;
  font-weight: bold;
  color: white;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 12px;
  color: rgba(255, 255, 255, 0.9);
}

.search-section {
  background-color: #fff;
  border-radius: 12px;
  padding: 10px;
  margin-bottom: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.filter-menu {
  margin-top: 10px;
}

.record-list {
  margin-top: 8px;
}

.record-card {
  background-color: #fff;
  border-radius: 12px;
  padding: 16px;
  margin-bottom: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  transition: transform 0.2s;
}

.record-card:active {
  transform: scale(0.98);
}

.record-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.record-meta {
  display: flex;
  align-items: center;
  gap: 8px;
}

.record-date {
  font-size: 12px;
  color: #969799;
}

.record-score {
  display: flex;
  align-items: center;
  gap: 6px;
}

.score-value {
  font-size: 18px;
  font-weight: bold;
  color: #1989fa;
}

.score-stars {
  display: flex;
  align-items: center;
}

.record-progress {
  margin: 12px 0;
}

.progress-info {
  display: flex;
  justify-content: space-between;
  font-size: 12px;
  color: #969799;
  margin-bottom: 6px;
}

.correct-count {
  font-size: 13px;
  color: #666;
  text-align: center;
  padding-top: 8px;
  border-top: 1px dashed #eee;
}
</style>